<!--
 * @Description:
 * @Author: zhailei
 * @Date: 2021-07-09 09:14:57
 * @LastEditTime: 2021-07-09 13:40:27
 * 
 * @FilePath: \-cloud-vue\src\pages\system\sysAppBasics\listPage.vue
-->
<template>
  <div>
    <a-row :gutter="24" style="margin: 0;">
      <!-- 操作 -->
      <!-- <div class="flex align-center">
				<a-button icon="play-circle" type="link" @click="handlePreview"> 预览</a-button>
				<a-button icon="eye" type="link" @click="handleOpenJsonModal">查看json</a-button>
			</div> -->
      <a-divider style="margin: 0;" />
      <!-- 右侧数据面板 -->
      <a-col :span="18" class="left-box">
        <div class="table-height" style="margin-bottom: 10px;">
          <div class="right-btn-box">
            <span
              :class="{
                'icon-box': true,
                'selected-icon': platformKey === 'desktop',
              }"
              @click="changePlatform('desktop')"
            >
              <a-icon type="desktop"></a-icon> 桌面端
            </span>
            <span
              :class="{
                'icon-box': true,
                'selected-icon': platformKey === 'mobile',
              }"
              @click="changePlatform('mobile')"
            >
              <a-icon type="mobile"></a-icon> 移动端
            </span>
          </div>
          <a-divider
            orientation="left"
            style="margin: 10px 0 0; padding: 16px 0;"
          >
            {{ $ct("ListConfiguration", "列表配置") }}
          </a-divider>
          <a-table
            :columns="$toI18nFormat(columnsList)"
            rowKey="filed"
            :data-source="dataColumnField"
            :pagination="false"
            :scroll="{ y: 'calc(50vh - 160px)' }"
            size="small"
          >
            <template slot="renderFiledName" slot-scope="text, record, index">
              <a-input
                v-if="formType === 'viewData'"
                v-model="record['filedName']"
                @change="handleChange($event.target.value, record, 'filedName')"
              />
              <template v-else>
                {{ text }}
              </template>
            </template>

            <template
              v-for="(item, index) in $toI18nFormat(columnsList)"
              :slot="item.slotName"
            >
              <span>{{ $ct(item.slotName, item.defaultTitle) }}</span>
            </template>

            <template slot="renderDrag" slot-scope="text, record, index">
              <a-icon
                type="arrow-up"
                class="margin-right-xs"
                :class="[index == 0 ? 'arrowHidden' : 'arrowShow']"
                @click="arrowButton(record, index, 'up')"
              />
              <a-icon
                type="arrow-down"
                :class="[
                  index == dataField.length - 1 ? 'arrowHidden' : 'arrowShow',
                ]"
                @click="arrowButton(record, index, 'down')"
              />
            </template>
            <template slot="renderAlign" slot-scope="text, record, index">
              <a-select
                v-model="text"
                style="width: 80px"
                @change="handleChange($event, record, 'align')"
              >
                <a-select-option value="left">
                  {{ $ct("AlignLeft", "左对齐") }}
                </a-select-option>
                <a-select-option value="center">
                  {{ $ct("FormCentre", "居中") }}
                </a-select-option>
                <a-select-option value="right">
                  {{ $ct("AlignRight", "右对齐") }}
                </a-select-option>
              </a-select>
            </template>
            <template slot="renderSort" slot-scope="text, record, index">
              <a-checkbox
                :defaultChecked="text"
                @change="handleChange($event.target.checked, record, 'sort')"
              ></a-checkbox>
            </template>
            <template slot="renderWidth" slot-scope="text, record, index">
              <a-input-number
                style="width: 80px !important;"
                :value="text"
                :min="0"
                :max="300"
                @change="handleChange($event, record, 'width')"
              />
            </template>
            <template slot="renderFixed" slot-scope="text, record, index">
              <a-select
                v-model="text"
                style="width: 60px"
                @change="handleChange($event, record, 'fixed')"
              >
                <a-select-option value="left">{{
                  $ct("Left", "左")
                }}</a-select-option>
                <a-select-option value="right">{{
                  $ct("right", "右")
                }}</a-select-option>
                <a-select-option value="">/</a-select-option>
              </a-select>
            </template>
          </a-table>
        </div>
        <div class="table-height">
          <a-divider orientation="left" style="margin: 0; padding: 16px 0;">
            {{ $ct("QueryConfiguration", "查询配置") }}
          </a-divider>
          <a-table
            :columns="$toI18nFormat(columnsSearch)"
            rowKey="filed"
            :data-source="dataColumnSearch"
            :pagination="false"
            :scroll="{ y: 'calc(50vh - 160px)' }"
            size="small"
          >
            <template slot="renderFiledName" slot-scope="text, record, index">
              <a-input
                v-if="formType === 'viewData'"
                v-model="record['filedName']"
                @change="handleChange($event.target.value, record, 'filedName')"
              />
              <template v-else>
                {{ text }}
              </template>
            </template>

            <template
              v-for="(item, index) in $toI18nFormat(columnsSearch)"
              :slot="item.slotName"
            >
              <span>{{ $ct(item.slotName, item.defaultTitle) }}</span>
            </template>

            <template slot="renderType" slot-scope="text, record, index">
              <a-select
                v-model="text"
                style="width: 150px"
                @change="handleChange($event, record, 'type')"
              >
                <a-select-option value="contain">{{
                  $ct("vague", "模糊")
                }}</a-select-option>
                <a-select-option value="equal">{{
                  $ct("BeEqualTo", "等于")
                }}</a-select-option>
                <a-select-option value="range" v-if="isDate(record.filedType)"
                  >范围</a-select-option
                >
              </a-select>
            </template>
          </a-table>
        </div>
      </a-col>
      <!-- 左侧操作面板 -->
      <a-col :span="6" class="right-box">
        <a-tabs
          class="tab-box"
          :activeKey="activeKey"
          @change="(e) => $emit('activeKeyChange', e)"
        >
          <a-tab-pane key="1" :tab="$ct('ListField', '列表字段')">
            <a-table
              :columns="$toI18nFormat(listField)"
              rowKey="filed"
              :data-source="dataSource"
              :pagination="false"
              :rowSelection="rowSelection"
              size="small"
            >
              <template
                v-for="(item, index) in $toI18nFormat(listField)"
                :slot="item.slotName"
              >
                <span>{{ $ct(item.slotName, item.defaultTitle) }}</span>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane
            key="2"
            :tab="$ct('QueryField', '查询字段')"
            rowKey="filed"
            force-render
          >
            <a-table
              :columns="$toI18nFormat(searchField)"
              rowKey="filed"
              :data-source="dataSourceSearch"
              :pagination="false"
              :rowSelection="rowSelectionSearch"
              size="small"
            >
              <template
                v-for="(item, index) in $toI18nFormat(searchField)"
                :slot="item.slotName"
              >
                <span>{{ $ct(item.slotName, item.defaultTitle) }}</span>
              </template>
            </a-table>
            <a-divider>{{ $ct("QueryConfiguration", "查询配置") }}</a-divider>

            <a-form-item :label="$ct('MergeType', '合并类型')">
              <a-tooltip placement="top">
                <template slot="title">
                  <span>
                    {{ $ct("MergeQueryBox", "合并查询框") }}:
                    {{
                      $ct(
                        "MergeQueryBoxMessage",
                        "合并成一个输入框，默认使用模糊查询。"
                      )
                    }}<br />
                    {{ $ct("SelectFieldQuery", "选择字段查询") }}:{{
                      $ct(
                        "SelectFieldQueryMessage",
                        "当查询框超出设定数量上限的时候，会合并成一个下拉框和一个输入框。"
                      )
                    }}
                  </span>
                </template>
                <a-icon
                  type="question-circle"
                  style="position: absolute;top: -36px;left: 63px;"
                />
              </a-tooltip>
              <a-select
                :allowClear="true"
                style="width: 100%;"
                v-model="queryType"
              >
                <a-select-option value="mergeQuery">
                  {{ $ct("MergeQueryBox", "合并查询框") }}
                </a-select-option>
                <a-select-option value="selectQuery">
                  {{ $ct("SelectFieldQuery", "选择字段查询") }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              v-show="queryType === 'selectQuery'"
              :label="$ct('MaximumQuantity', '数量上限')"
            >
              <a-input-number
                v-model="upperLimit"
                :min="3"
                placeholder="请输入数量上限"
              />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="formType !== 'viewData'"
            key="3"
            :tab="$ct('ListConfiguration', '列表配置')"
            force-render
          >
            <formGenPro
              ref="formGenPro"
              :type="platformKey"
              :listFiled="dataSource"
              :selectItem="listProData"
              @change="onFormChange"
            ></formGenPro>
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>
    <preview-table
      ref="previewTable"
      :visible="tableVisible"
      :listData="dataColumnField"
      :searchData="dataColumnSearch"
      :listProData="listProData"
      :basicData="basicData"
    ></preview-table>
  </div>
</template>

<script>
import previewTable from "./previewTable.vue";
import { listPro } from "@/components/TopVUI/k-form-design/packages/KFormDesign/config/listPro";
import formGenPro from "@/components/TopVUI/k-form-design/packages/KFormDesign/module/codeFormGenerationProperties.vue";
const columnsList = [
  {
    title: "排序",
    width: 80,
    dataIndex: "drag",
    align: "center",
    scopedSlots: {
      customRender: "renderDrag",
    },
  },
  {
    dataIndex: "filedName",
    title: "列名",
    langCode: "ColumnName",
    scopedSlots: {
      customRender: "renderFiledName",
    },
  },
  {
    title: "字段",
    dataIndex: "filed",
    langCode: "field",
  },
  {
    title: "对齐方式",
    dataIndex: "align",
    width: 100,
    scopedSlots: {
      customRender: "renderAlign",
    },
    langCode: "Alignment",
  },
  {
    title: "排序",
    dataIndex: "sort",
    align: "center",
    width: 80,
    scopedSlots: {
      customRender: "renderSort",
    },
    langCode: "sort",
  },
  {
    title: "宽度(px)",
    dataIndex: "width",
    width: 100,
    scopedSlots: {
      customRender: "renderWidth",
    },
    langCode: "width",
  },
  // {
  // 	title: '左右固定',
  // 	dataIndex: 'fixed',
  // 	width: 100,
  // 	scopedSlots: {
  // 	  customRender: 'renderFixed',
  // 	},
  // 	langCode:"FixedLeftRight"
  // }
];
const columnsSearch = [
  {
    dataIndex: "filedName",
    title: "列名",
    langCode: "ColumnName",
    scopedSlots: {
      customRender: "renderFiledName",
    },
  },
  {
    title: "字段",
    dataIndex: "filed",
    langCode: "field",
  },
  {
    title: "查询方式",
    dataIndex: "type",
    scopedSlots: {
      customRender: "renderType",
    },
    langCode: "QueryMethod",
  },
];
const listField = [
  {
    dataIndex: "filedName",
    title: "列表字段",
    langCode: "ListField",
  },
];
const searchField = [
  {
    dataIndex: "filedName",
    title: "查询字段",
    langCode: "QueryField",
  },
];
export default {
  props: {
    basicData: {
      type: Object,
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
    dataField: {
      type: Array,
      default: () => [],
    },
    dataSearch: {
      type: Array,
      default: () => [],
    },
    activeKey: {
      type: String || Number,
      default: 1,
    },
    platformKey: {
      type: String,
      default: "mobile",
    },
    formType: {
      type: String,
    },
  },
  components: { formGenPro, previewTable },
  data() {
    return {
      columnsList,
      columnsSearch,
      listField,
      searchField,
      dataSourceSearch: [],
      selectedRowKeys: [],
      selectedRows: [],
      selectedRowKeysSearch: [],
      selectedRowsSearch: [],
      listProData: {},
      tableVisible: false,
      dataColumnField: [],
      dataColumnSearch: [],
      pageClientHeight: 0,
      isAllSelect: false,
      queryType: "",
      upperLimit: 3,
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      };
    },
    rowSelectionSearch() {
      return {
        selectedRowKeys: this.selectedRowKeysSearch,
        onChange: this.onSelectChangeSearch,
      };
    },
    isDate() {
      return (e) => {
        return e === "date";
      };
    },
  },
  watch: {
    dataSource: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        let data = newVal.filter((s) => s.filed != "action");
        this.dataSourceSearch = data.filter((item) => {
          if (
            !~["PopoverGrid", "ComboGrid", "switch", "area"].indexOf(
              item.filedType
            )
          ) {
            return item;
          }
        });
        // this.listProData = this.basicData ? this.basicData : listPro
        // 修改内存地址
        let obj = Object.assign({}, listPro);
        obj.topButtonList = obj.topButtonList.concat();
        obj.lineButtonList = obj.lineButtonList.concat();
        this.listProData =
          JSON.stringify(this.listProData) == "{}" ? obj : this.listProData;
      },
    },
    dataField: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        this.dealWithData(newVal);
      },
    },
    dataSearch: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        this.dealWithSearch(newVal);
      },
    },
    listProData: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        let data = (this.dataSource || []).find((d) => d.filed === "action");
        let datakey = (this.dataSource || []).findIndex(
          (d) => d.filed === "action"
        );
        let rowkey = (this.selectedRows || []).findIndex(
          (r) => r.filed === "action"
        );
        let rowkeys = (this.selectedRowKeys || []).findIndex(
          (r) => r === "action"
        );
        if (newVal.showlineButton && rowkey == -1) {
          this.selectedRows.push(data);
          this.selectedRowKeys.push(data.filed);
        } else if (!newVal.showlineButton && rowkeys != -1) {
          this.selectedRows.splice(rowkey, 1);
          this.selectedRowKeys.splice(rowkeys, 1);
        }
        this.$emit("dataChange", this.selectedRows, "list", "mobile");
      },
    },
    dataColumnSearch: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        for (let i = 0; i < this.dataSourceSearch.length; i++) {
          for (let j = 0; j < newVal.length; j++) {
            if (this.dataSourceSearch[i].filed === newVal[j].filed) {
              this.dataSourceSearch[i].type = newVal[j].type;
            }
          }
        }
      },
    },
  },
  mounted() {},
  methods: {
    allSelect() {
      this.$nextTick(() => {
        if (!this.isAllSelect) {
          this.selectedRows = this.dataSource;
          this.selectedRowKeys = this.dataSource.map((item) => item.filed);
          let key = this.selectedRows.findIndex((j) => j.filed == "action");
          this.listProData.showlineButton = key == -1 ? false : true;
          this.$emit("dataChange", this.selectedRows, "list", "mobile");
          this.isAllSelect = true;
        }
      });
    },
    // 用于数据视图获取数据
    viewSelect() {
      this.$nextTick(() => {
        this.selectedRows = this.dataSource;
        this.selectedRowKeys = this.dataSource.map((item) => item.filed);
        let key = this.selectedRows.findIndex((j) => j.filed == "action");
        this.listProData.showlineButton = key == -1 ? false : true;
        this.$emit("dataChange", this.selectedRows, "list", "desktop");
      });
    },
    init() {
      //重置数据
      this.selectedRows = [];
      this.selectedRowKeys = [];
      this.selectedRowsSearch = [];
      this.selectedRowKeysSearch = [];
    },
    // 列表表格排序
    arrowButton(record, index, type) {
      const listData = [...this.dataColumnField];
      let key = listData.findIndex((val) => val.filed == record.filed);
      if (type == "up" && index != 0) {
        // 左边是元素在数组中的原本的排列顺序 右边是自己希望的排列顺序。
        [listData[key - 1], listData[key]] = [listData[key], listData[key - 1]];
      } else if (type == "down" && index != listData.length - 1) {
        [listData[key], listData[key + 1]] = [listData[key + 1], listData[key]];
      }
      this.dataColumnField = listData;
      this.selectedRows = listData;
    },
    // 处理列表表格数据
    dealWithData(newVal) {
      let data = [];
      for (let item of newVal) {
        for (let data of this.dataSource) {
          if (item.filed === data.filed) item.filedName = data.filedName;
        }
      }
      this.dataColumnField = JSON.parse(JSON.stringify([...newVal]));
      this.dataColumnField.forEach((item, index) => {
        let key = (this.dataSource || []).findIndex(
          (j) => j.filed === item.filed
        );
        if (key != -1) {
          // item.filedName = this.dataSource[key].filedName
        } else {
          let rowkey = (this.selectedRows || []).findIndex(
            (r) => r.filed === item.filed
          );
          let rowkeys = (this.selectedRowKeys || []).findIndex(
            (r) => r === item.filed
          );
          this.selectedRows.splice(rowkey, 1);
          this.selectedRowKeys.splice(rowkeys, 1);
          data.push(item.filed);
        }
      });
      data.forEach((e) => {
        this.dataColumnField.splice(
          this.dataColumnField.findIndex((el) => el.filed == e),
          1
        );
      });
      this.$emit("dataChange", this.selectedRows, "list", "mobile");
    },
    // 处理搜索表格数据
    dealWithSearch(newVal) {
      let data = [];
      this.dataColumnSearch = JSON.parse(JSON.stringify([...newVal]));
      this.dataColumnSearch.forEach((item, index) => {
        let key = (this.dataSource || []).findIndex(
          (j) => j.filed === item.filed
        );
        if (key != -1) {
          // item.filedName = this.dataSource[key].filedName
        } else {
          let rowkey = (this.selectedRowsSearch || []).findIndex(
            (r) => r.filed === item.filed
          );
          let rowkeys = (this.selectedRowKeysSearch || []).findIndex(
            (r) => r === item.filed
          );
          this.selectedRowsSearch.splice(rowkey, 1);
          this.selectedRowKeysSearch.splice(rowkeys, 1);
          this.dataColumnSearch.splice(index, 1);
          data.push(item.filed);
        }
      });
      data.forEach((e) => {
        this.dataColumnSearch.splice(
          this.dataColumnSearch.findIndex((el) => el.filed == e),
          1
        );
      });
      this.$emit("dataChange", this.selectedRowsSearch, "search", "mobile");
    },
    handlePreview() {
      this.$refs.previewTable.visible = true;
    },
    handleOpenJsonModal() {
      console.log("查看json");
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows;
      this.selectedRowKeys = selectedRowKeys;
      let key = selectedRows.findIndex((j) => j.filed == "action");
      this.listProData.showlineButton = key == -1 ? false : true;
      this.$emit("dataChange", selectedRows, "list", "mobile");
    },
    onSelectChangeSearch(selectedRowKeys, selectedRows) {
      this.selectedRowsSearch = selectedRows;
      this.selectedRowKeysSearch = selectedRowKeys;
      this.$emit("dataChange", selectedRows, "search", "mobile");
    },
    changeCheck(item) {
      item.checked = !item.checked;
    },
    handleChange(e, record, key) {
      record[key] = e;
    },
    onFormChange(e, key) {
      this.listProData[key] = e;
    },
    getListData() {
      return {
        listData: this.dataColumnField,
        searchData: {
          queryType: this.queryType,
          upperLimit: this.upperLimit,
          list: this.dataColumnSearch,
        },
        listProData: this.listProData,
      };
    },
    changePlatform(e) {
      this.$emit("changePlatform", e);
    },
  },
};
</script>

<style lang="scss" scoped>
.arrowHidden {
  color: #e7e7e7;
}
.arrowShow {
  color: #606266;
  &:hover {
    color: #1890ff;
  }
}
.left-box {
  padding: 0 !important;
  margin: 10px;
  height: calc(100vh - 77px);
}
.right-box {
  padding: 0 !important;
  width: calc(25% - 30px);
  height: calc(100vh - 77px);
  background-color: #fff;
  margin: 10px 0;
}
/deep/.ant-tabs-tabpane {
  padding: 0 10px;
}
/deep/.ant-tabs-tabpane {
  overflow: auto;
  height: calc(100vh - 132px);
}
.tab-box /deep/.ant-tabs-nav {
  width: 100%;
}
.tab-box /deep/.ant-tabs-nav > div {
  display: flex !important;
  width: 100%;
}
.tab-box /deep/.ant-tabs-tab {
  flex: 1;
  text-align: center;
}
.table-height {
  background-color: #fff;
  height: calc(50% - 5px);
  padding: 5px;
}
.right-btn-box {
  display: flex;
  position: absolute;
  right: 0;
  z-index: 10;
}
.icon-box {
  color: #1890ff;
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
  font-size: 14px;
}
.selected-icon {
  color: #1890ff;
  padding: 5px 10px;
  margin: 0 5px;
  background-color: #f0f2f5;
  border-radius: 5px;
  cursor: pointer;
}
</style>
